package com.qyhl.cloud.webtv.module_integral.wallet.money;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qyhl.cloud.webtv.module_integral.R;
import com.qyhl.cloud.webtv.module_integral.R2;
import com.qyhl.cloud.webtv.module_integral.app.IntegralApplication;
import com.qyhl.cloud.webtv.module_integral.common.IntergralUrl;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.intergral.FrowarkHistoryBean;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * A simple {@link Fragment} subclass.
 */
public class FforwardHistoryFragment extends BaseFragment {
    @BindView(R2.id.load_mask)
    LoadingLayout loadingMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;

    /**
     * 最后一条日期
     */
    private String lastdate = "";
    private final String tag = "FforwardHistoryFragmentTag";
    private List<FrowarkHistoryBean> mdata;
    private CommonAdapter<FrowarkHistoryBean> adapter;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.inter_fragment_fforward_history, container, false);
    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void create() {

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        initView();
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    private void initView() {
        loadingMask.setStatus(LoadingLayout.Loading);
        loadingMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingMask.setStatus(LoadingLayout.Loading);
                lastdate = "";
                getData(lastdate);
            }
        });

        refresh.setEnableLoadMore(true);
        refresh.setEnableRefresh(true);
        //刷新中禁止操作
        refresh.setDisableContentWhenRefresh(true);
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        //下拉刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                lastdate = "";
                getData(lastdate);
            }
        });

        //加载更多
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getData(lastdate);
            }
        });

        mdata = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter = new CommonAdapter<FrowarkHistoryBean>(getContext(),
                R.layout.inter_fforwardhistory_layout, mdata) {
            @Override
            protected void convert(ViewHolder viewHolder, FrowarkHistoryBean bean, int position) {
                viewHolder.setText(R.id.cashnum, "现金" + bean.getMoney() + "元");
                viewHolder.setText(R.id.cashtime, bean.getGmtCreate());
                viewHolder.setText(R.id.cashstatus, getProcess(bean.getProcess()));
            }
        });

        getData(lastdate);
    }

    private String getProcess(int process) {
        switch (process) {
            case 1:
                return "待审核";
            case 2:
                return "提现中";
            case 3:
                return "审核不通过";
            case 4:
                return "提现成功";
            case 5:
                return "提现失败";
            case 6:
                return "已退款";
            default:
        }
        return "处理中";
    }

    private void getData(String lastdate) {
        if (NetUtil.isNetworkAvalible(IntegralApplication.getApp())) {
            Map<String, String> map = DESedeUtil.encodeMapUrl(IntergralUrl.INTEGRAL_URL);
            JSONObject jsonObject = new JSONObject();
            try {
                String userName = CommonUtils.getInstance().getUserName();
                jsonObject.put("name", "cashHistory");
                jsonObject.put("version", PathConfigConstant.version);
                jsonObject.put("username", userName);
                jsonObject.put("siteId", CommonUtils.getInstance().getSite());
                jsonObject.put("lastDate", lastdate);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            EasyHttp.post(map.get(DESedeUtil.URL))
                    .isDecrypt(true)
                    .decryptKet(map.get(DESedeUtil.CODEKEY))
                    .upBytes(DESedeUtil.encryptMode(map.get(DESedeUtil.CODEKEY),
                            jsonObject.toString()
                    ))
                    .execute(new SimpleCallBack<List<FrowarkHistoryBean>>() {
                        @Override
                        public void onError(ApiException e) {
                            getDataError(TextUtils.isEmpty(e.getMessage()) ? "请求失败" : e.getMessage());
                        }

                        @Override
                        public void onSuccess(List<FrowarkHistoryBean> frowarkHistoryBeans) {
                            getDataSuccess(frowarkHistoryBeans);
                        }
                    });


        } else {
            getDataError("无网络连接，请检查您的网络...");
        }
    }

    private void getDataSuccess(List<FrowarkHistoryBean> data) {
        loadingMask.setStatus(LoadingLayout.Success);
        refresh.finishRefresh();
        refresh.finishLoadMore();

        if (data == null || data.isEmpty()) {
            if (lastdate.equals("")) {
                loadingMask.setEmptyText("");
                loadingMask.setEmptyImage(R.drawable.takoutrecord_norecord_pic);
                loadingMask.setStatus(LoadingLayout.Empty);
            } else {
                Toasty.normal(getContext(), "没有更多了").show();
            }
        } else {
            if (lastdate.equals("")) {
                mdata.clear();
            }
            mdata.addAll(data);
            adapter.notifyDataSetChanged();

            //记录最后一条日期
            lastdate = data.get(data.size() - 1).getGmtCreate();
        }
    }

    private void getDataError(String message) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        if (lastdate.equals("")) {
            loadingMask.setErrorText(message);
            loadingMask.setReloadButtonText("点击重试");
            loadingMask.setErrorImage(R.drawable.error_content);
            loadingMask.setStatus(LoadingLayout.Error);
        } else {
            Toasty.normal(getContext(), message).show();
        }
    }
}
